
using System;
using System.IO;
using Gtk;

namespace wc_gui_input
{
	
	public class list_pages : Gtk.Window
	{
		protected Gtk.ComboBox combo_page;
		protected Gtk.Button but_edit;
		protected Gtk.Button but_delete;
		protected Gtk.Entry entry_title;
		protected Gtk.ComboBox combo_location;
		protected Gtk.Button but_add;

		protected ListStore store_filenames;
		protected ListStore store_cat;
		protected ListStore store_cat2;	
		protected String cat_filename;
		protected String cat_title_name;
		protected int cat_num;
		protected String active_filename;
		protected String page_title;
		
		// Lists all pages in chosen category
		// vars:
		// page_filename is category text db, contains list of all pages it owns in order
		public list_pages(String page_filename, string categ_title, int categ_num) :
				base("")
		{
			Stetic.Gui.Build(this, typeof(wc_gui_input.list_pages));
			cat_filename=page_filename;
			cat_title_name=categ_title;
			cat_num=categ_num;

			// store holds values
        	store_filenames = new ListStore(typeof (string));
        	store_cat = new ListStore(typeof (string));
        	store_cat2 = new ListStore(typeof (string));
			
			init_widgets();
		}
		
		// initializes widgets
		protected virtual void init_widgets() {
			TextReader categ;
			try { // config file to read from
	      		categ = new StreamReader(cat_filename);  
	    	} catch(FileNotFoundException exc) { 
	      		Console.WriteLine(exc.Message); 
	      		return; 
	    	}
	    	// initialize for combo_box
	    	CellRendererText cell = new CellRendererText();
	        
	        // erase old data
			entry_title.Text="";
	        store_cat.Clear();
	        store_cat2.Clear();
	        store_filenames.Clear();
	        
	        // initialize modify/delete existing category
	        combo_page.Clear();
	    	combo_page.PackStart(cell, false);
	        combo_page.AddAttribute(cell, "text", 0);
	        
			// initialize new category location
	        combo_location.Clear();
	    	combo_location.PackStart(cell, false);
	        combo_location.AddAttribute(cell, "text", 0);
	        
	        // assign stores
	        combo_page.Model = store_cat;
	        combo_location.Model = store_cat2;
	        
	        // populate stores into combo box
	        int i=0;
	    	while (categ.Peek() != -1) {
	    		String temp = categ.ReadLine();
				store_filenames.AppendValues(0,temp.IndexOf(' '));
	    		String temp2 = temp.Substring(temp.IndexOf(' ')+1);
	    		store_cat.AppendValues(temp2.Substring(0,temp2.Length));
	    		store_cat2.AppendValues("\n");
	    		store_cat2.AppendValues(temp2.Substring(0,temp2.Length));
	    		if (i==0) { // store for default filename to be sent for editing
	    			active_filename=temp.Substring(0,temp.IndexOf(' '));
	    			page_title=temp2.Substring(0,temp2.Length);
	    		}
				i++;
	    	}
	    	store_cat2.AppendValues("\n");
			categ.Close();
			
			// set combo boxes to have initial active item
			combo_page.Active = 0;
			combo_location.Active = 0;
		}
		
		// User clicked add page
		// creates edit_page window with flag var "modify" as false
		protected virtual void OnButAddClicked(object sender, System.EventArgs e)
		{
			//  If no text is in title, halt adding.
		if (entry_title.Text.Trim() == "") {
			MessageDialog md = new MessageDialog (this,
									DialogFlags.DestroyWithParent,
                                   MessageType.Error, 
                                      ButtonsType.Close, "Page must have a title.");
			int result = md.Run ();
			md.Destroy();
			return;
		}
		
		//  If location is not empty space, cannot overwrite another page as location
		if (combo_location.ActiveText.Trim() != "") {
			MessageDialog md = new MessageDialog (this,
									DialogFlags.DestroyWithParent,
                                   MessageType.Error, 
                                      ButtonsType.Close, "Select a location above or below the selected page.");
			int result = md.Run ();
			md.Destroy();
			return;
		}
		new wc_gui_input.edit_page(make_filename(),entry_title.Text,combo_location.Active/2, false, cat_title_name, cat_num);
		
		init_widgets();
		
		this.Destroy();// cannot get file to reload properly
		}

		// User clicked edit page
		// creates edit_page window with flag var "modify" as true
		protected virtual void OnButEditClicked(object sender, System.EventArgs e)
		{
			// send the category's filename -4-4 since "cat_" is 4, and ".txt" is 4
			new wc_gui_input.edit_page(active_filename,page_title,-1, true, cat_title_name, cat_num);
			//test tests = new test();// trying to get html working
		}

		// user clicked delete page
		// removes page from categories text db and also removes page
		protected virtual void OnButDeleteClicked(object sender, System.EventArgs e)
		{
			String filename_to_delete="";
			String line="";
			TextReader infile;// infile is page ( category --> page )
			
			try {
	 			infile = new StreamReader(cat_filename); // file to read from 
	    	} catch(FileNotFoundException exc) { 
	      		Console.WriteLine(exc.Message); 
	      		return; 
	    	}

			FileStream outfile; // file to write to
			try {
				outfile = new FileStream(cat_filename+".backup", FileMode.OpenOrCreate, FileAccess.Write);
			} catch(UnauthorizedAccessException exc) {
				Console.WriteLine(exc.Message);
				return;
			}
			
			// Create a new stream to write to the file
			StreamWriter sw = new StreamWriter(outfile);

	        int line_count = 0;
	        while (infile.Peek() != -1) // reading file to write in formatted html to file
			{
				String temp = infile.ReadLine();
				if (line_count != combo_page.Active) {
					// skip writing the category that user selected
					sw.WriteLine(temp);
				} else {
					// remember page filename
					filename_to_delete=temp.Substring(0,temp.IndexOf(' '));
				}
				line_count++;// increase # to append next template text file
			}
			infile.Close();
			sw.Close();
			outfile.Close();

			// see if file contains picture to delete
			try {
	 			infile = new StreamReader(filename_to_delete); // file to read from 
	    	} catch(FileNotFoundException exc) { 
	      		Console.WriteLine(exc.Message); 
	      		return; 
	    	}

			while (infile.Peek() != -1) { // parse html
				line=infile.ReadLine();
				if (line=="<!-- CONTENT -->") { 
				// this is the line before the line with the content
					line=infile.ReadLine();// get to line with content
					
					// test for picture
					if (line.StartsWith("<img")) {
						// delete picture, if it exists
						try {
							File.Delete(line.Substring(line.IndexOf("src=")+5,line.IndexOf(">")-1-(line.IndexOf("src=")+5))); 
				    	} catch(FileNotFoundException exc) { 
				      		Console.WriteLine(exc.Message); 
				      		return; 
				    	}	
					}					
					break;
				}
			}
			infile.Close();

			File.Delete(cat_filename);
			File.Delete(filename_to_delete);
			File.Move(cat_filename+".backup",cat_filename);

			// Now remove file from menu (dynamic.js)
			
			try {
	 			infile = new StreamReader("dynamic.js"); // file to read from 
	    	} catch(FileNotFoundException exc) {
	      		Console.WriteLine(exc.Message);
	      		return;
	    	}

			try {
				outfile = new FileStream("dynamic.js.backup", FileMode.OpenOrCreate, FileAccess.Write);
			} catch(UnauthorizedAccessException exc) {
				Console.WriteLine(exc.Message);
				return;
			}
			// Create a new stream to write to the file
			sw = new StreamWriter(outfile);

	        while (infile.Peek() != -1) { // reading file to write in formatted html to file
				line = infile.ReadLine();
				if (line.Equals("document.writeln('      <li><a href=\""+filename_to_delete+"\">"+combo_page.ActiveText+"</a></li>');")) {
					// the page we want to remove, go to next line
					line=infile.ReadLine();
				}
				sw.WriteLine(line);
			}
			infile.Close();
			sw.Close();
			outfile.Close();

			File.Delete("dynamic.js");
			File.Move("dynamic.js.backup","dynamic.js");

			init_widgets();
		}

		protected virtual void OnComboLocationChanged(object sender, System.EventArgs e)
		{
		}

		// reloads combo box with all pages, for instance, after a page is deleted
		protected virtual void OnComboPageChanged(object sender, System.EventArgs e)
		{
			TextReader categ;
			try {// config file to read from
	      		categ = new StreamReader(cat_filename);  
	    	} catch(FileNotFoundException exc) { 
	      		Console.WriteLine(exc.Message); 
	      		return; 
	    	}
	        
	        int i=0;
	    	while (categ.Peek() != -1) {
	    		String temp = categ.ReadLine();
				String temp2 = temp.Substring(temp.IndexOf(' ')+1);
	    		if (i==combo_page.Active) { // store for default filename to be sent for editing
					active_filename=temp.Substring(0,temp.IndexOf(' '));
	    			page_title=temp2.Substring(0,temp2.Length);
	    		}
				i++;
	    	}
		}
		
		// make filename compatible with program
		// remove spaces, truncate
		protected virtual String make_filename() {	
			// send the category's filename -4-4 since "cat_" is 4, and ".txt" is 4
			String new_title=entry_title.Text.ToLower();
			if (new_title.Length>6)
				new_title=new_title.Substring(0,6);
			new_title.Replace(' ', '_');
			return cat_filename.Substring(4,(cat_filename.Length-4-4)).ToLower()+"_"+new_title+".html";		
		}
	}
	
}
